﻿// //   Copyright 2007-2011 Comdiv (F. Sadykov) - http://code.google.com/u/fagim.sadykov/
// //   Supported by Media Technology LTD 
// //    
// //   Licensed under the Apache License, Version 2.0 (the "License");
// //   you may not use this file except in compliance with the License.
// //   You may obtain a copy of the License at
// //    
// //        http://www.apache.org/licenses/LICENSE-2.0
// //    
// //   Unless required by applicable law or agreed to in writing, software
// //   distributed under the License is distributed on an "AS IS" BASIS,
// //   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// //   See the License for the specific language governing permissions and
// //   limitations under the License.
// //   
// //   MODIFICATIONS HAVE BEEN MADE TO THIS FILE

using System;
using Comdiv.QWeb.Binding;
using Comdiv.QWeb.Cache;
using Comdiv.QWeb.Serialization.Attributes;

namespace Comdiv.QWeb.Factory {
	[Serialize]
	public class ActionDescriptor : QWebStepDescriptor {
		private string _help;
		[IgnoreSerialize] public IAction Action { get; set; }

		public string ActionTypeName {
			get {
				if (null == Action) return null;
				return Action.GetType().AssemblyQualifiedName;
			}
		}


		public BindAttribute[] Binders { get; set; }

		public ActionTypeDescriptor TypeDescriptor { get; set; }

		[IgnoreSerialize] public override DateTime LastModified {
			get {
				if (Action is INotModifiedStateProvider) {
					return ((INotModifiedStateProvider) Action).LastModified;
				}
				return new DateTime();
			}
		}

		[IgnoreSerialize] public override string ETag {
			get { return ((INotModifiedStateProvider) Action).ETag; }
		}


		public override bool SupportNotModifiedState {
			get {
				if (null == Action) return false;
				if (Action is INotModifiedStateProvider) {
					return ((INotModifiedStateProvider) Action).SupportNotModifiedState;
				}
				return false;
			}
		}

		public string Help {
			get { return _help ?? ""; }
			set { _help = value; }
		}

		public void Bind(QWebContext context) {
			if (TypeDescriptor.SupportsBind) {
				var binder = TypeDescriptor.GetBinder();
				try {
					binder.Bind(this, context);
				}
				finally {
					TypeDescriptor.Factory.ReleaseBinder(binder);
				}
			}
		}

		public object Process(QWebContext context) {
			Bind(context);
			return Action.Process(context);
		}

		public void SetupBinders() {
			if (null != Binders) return;

			if (TypeDescriptor.SupportsBind) {
				var binder = TypeDescriptor.GetBinder() as DefaultActionBinder;
				if (null != binder) {
					binder.SetupBinders(this);
				}
			}
			Binders = Binders ?? new BindAttribute[] {};
		}
	}
}